﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;


namespace RayDen.Library.Core
{
    public static class Extensions
    {
        public static bool NameContains1(this string name, params string[] subs)
        {
            if (string.IsNullOrWhiteSpace(name))
                return false;
            return subs.Select(item => item.ToLower()).Any(name.ToLower().Contains);
        }


        public static bool NameContains(this string name, params string[] subs)
        {
            if (string.IsNullOrWhiteSpace(name))
                return false;
            var nm = name.ToLower();

            for (int index = 0; index < subs.Length; index++)
            {
                if (nm.Contains(subs[index].ToLower()))
                    return true;
            }
            return false;
            //return subs.Select(item => item.ToLower()).Any(name.ToLower().Contains);
        }

        public static string Aggregate(this string[] strings, int startingIndex, string separator)
        {
            return strings.Skip(startingIndex - 1).Aggregate((a, b) => a + separator + b);
        }


        public static string Aggregate<TType>(this TType[] strings, int startingIndex, string separator)
        {
            return strings.Skip(startingIndex - 1).Select(item => item.ToString()).Aggregate((a, b) => a + separator + b);
        }
        public static byte[] GetBytes(this string str)
        {
            var bytes = new byte[str.Length * sizeof(char)];
            Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
            return bytes;
        }
        public static string GetString(this byte[] bytes)
        {
            char[] chars = new char[bytes.Length / sizeof(char)];
            System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
            return new string(chars);
        }

        public static void PartialSort<T>(this IList<T> array, Comparison<T> cmp, int startIndex, int endIndex)
        {
            T[] sortedList = new T[(endIndex - startIndex)];

            for (int i = startIndex; i < endIndex; i++)
            {
                sortedList[i - startIndex] = array[i];
            }
            var newList = new List<T>(sortedList);
            newList.Sort(cmp);
            sortedList = newList.ToArray();

            for (int i = 0; i < sortedList.Length; i++)
                array[i + startIndex] = sortedList[i];
        }

        public static string ReadWhile(this TextReader reader, Func<char, bool> predicate)
        {
            var ch = (char)reader.Peek();
            var chars = new List<char>();
            while (predicate(ch))
            {
                ch = (char)reader.Read();
                chars.Add(ch);
            }
            return new string(chars.ToArray());
        }
    }
}
